<template>
    <div class="page-100 repair-equipment-layout">

        <div class="repair-content-part">
            <yd-cell-item>
                <p slot="left">报修设备:</p>
                <p @click="scanHandleClick" slot="right" class="blue-color">{{device}}</p>
            </yd-cell-item>
            <yd-cell-item>
                <p slot="left">报修机构:</p>
                <p slot="right" class="blue-color" @click="instHandlerClick">{{instName}}</p>
            </yd-cell-item>
            <yd-cell-item>
                <p slot="left">故障类型:</p>
                <p slot="right" class="blue-color" @click="faultHandler">{{faultTypeStr}}</p>
            </yd-cell-item>
            <div class="bottom-line"></div>
            <textarea id="textfocus"
                      @click="clickTextHandle"
                      v-on:focus="focusIpt"
                      v-on:blur="blurIpt"
                      v-model="desfault"
                      class="weui-textarea des-fault-part"
                      placeholder="请描述故障"
                      rows="3"
                      maxlength="200"></textarea>
            <!--图片显示组件-->
            <ImageShowComponent
                    :imageList="images"
                    :isShowDelLogo="true"
                    v-on:imageDeleteEvent="deleteImgHandler"/>
            <!--底部导航栏操作组件-->
            <MultimediaComponent
                    id="idmultimedia"
                    :isMultimediaFocus="isMultimediaFocus"
                    v-on:clickVoicePanel="clickVoicePanel"
                    v-on:clickPicture="clickPicture"
                    v-on:clickPhoto="clickPhoto"
                    v-on:touchStartAudio="touchStartAudio"
                    v-on:touchEndAudio="touchEndAudio"
                    v-on:clickKeyboard="clickKeyboard"/>
            <!--故障类型ActionSheet-->
            <yd-actionsheet :items="faultItems" v-model="isFaultSheet" cancel="取消"></yd-actionsheet>
            <!--发送按钮-->
            <yd-button  size="large" type="primary" @click.native="handleClick" style="background-color:#3cc8a8;color:white;height: 40px">发送</yd-button>
        </div>
    </div>
</template>

<script>
    import MultimediaComponent from "@/components/MultimediaComponent.vue";
    import ImageShowComponent from "@/components/ImageShowComponent.vue";
    import {machineUuidDetails,showFaultTypeSelect,orderApply,uploadQiNiuImage} from "../../pcof/post";
    import {rainAllowRecord,userInfoData,wxAccessToken,instObject,openId,repairEquipmentData} from '../../globalVariables'
    export default {
        name: "repairEquipment",
        data() {
            return {
                equipmentDetail:{},//设备查询报修之后的设备数据
                // images: [
                //     'http://static.ydcss.com/uploads/ydui/1.jpg',
                //     'http://static.ydcss.com/uploads/ydui/2.jpg',
                //     'http://static.ydcss.com/uploads/ydui/3.jpg'
                // ],
                // images: [
                //     "wxLocalResource://imageid123456789987654321", "wxLocalResource://imageid987654321123456789"
                // ]
                images: [],
                desfault: '',
                device: '请扫描二维码设备',
                equipUuid: '',
                faultTypeStr: '',
                faultTypeUuid: '',
                instName: '',
                instUuid: '',
                partnerUuid: '',
                isFocus: false,
                isMultimediaFocus: false,
                isFaultSheet: false,
                faultItems: [],
                idx: 0,
                serverIds: '',
                startTx: 0,
                startTy: 0,
                timer: null,
            }
        },
        components: {
            MultimediaComponent,
            ImageShowComponent,
        },
        directives: {
            focus: {
                inserted(element, binding) {
                    if (binding.value) {
                        element.focus()
                    } else {
                        element.blur()
                    }
                },
                componentUpdated(element, binding) {
                    if (binding.value) {
                        element.focus()
                    } else {
                        element.blur()
                    }
                },
            },
        },
        created() {
            if (localStorage.getItem(repairEquipmentData) !== null && localStorage.getItem(repairEquipmentData) !== '' && localStorage.getItem(repairEquipmentData) !== undefined) {
                this.desfault = localStorage.getItem(repairEquipmentData);
            }
            this.equipmentDetail=this.$route.params.equipmentDetail;

            this.showFaultTypeSelectFunc();
            if (localStorage.getItem(instObject) === null || localStorage.getItem(instObject) === '' || localStorage.getItem(instObject) === undefined) {
                this.instName = JSON.parse(localStorage.getItem(userInfoData)).bankName;
                this.instUuid = JSON.parse(localStorage.getItem(userInfoData)).bankUuid;
                this.partnerUuid = JSON.parse(localStorage.getItem(userInfoData)).partnerUuid;
            } else {
                this.instName = JSON.parse(localStorage.getItem(instObject)).name;
                this.instUuid = JSON.parse(localStorage.getItem(instObject)).uuid;
                this.partnerUuid = JSON.parse(localStorage.getItem(instObject)).partnerUuid;
            }

            if (this.equipmentDetail === null || this.equipmentDetail === '' || this.equipmentDetail === undefined) {

            } else {
                this.equipUuid = this.equipmentDetail.machineUuid;
                this.instName = this.equipmentDetail.instName;
                this.instUuid = this.equipmentDetail.instUuid;
                this.device = this.equipmentDetail.bussinessName + ' '+ this.equipmentDetail.name;
                this.partnerUuid = this.equipmentDetail.partnerUuid;
            }
            console.log('-------------------------------');
            console.log(this.partnerUuid);
        },
        beforeRouteLeave(to,from,next) {
            // this.isFocus = false;
            // document.getElementById('textfocus').blur();
            document.activeElement.blur();
            if (to.path.indexOf('equipment_Detailrecord') !== -1 || to.path === '/inst_list/repairEquipMent' || to.path === '/repair_task') {
                next();
            } else {
                // const answer = window.confirm('离开后已填写的内容将会丢失');
                // if (answer) {
                //     next()
                // } else {
                //     next(false)
                // }
                weui.confirm('离开后已填写的内容将会丢失', {
                    title: '',
                    buttons: [{
                        label: '离开',
                        type: 'primary',
                        onClick: function () {
                            console.log('no');
                            localStorage.removeItem(instObject);
                            localStorage.removeItem(repairEquipmentData);
                            next();
                        }
                    }, {
                        label: '取消',
                        type: 'default',
                        onClick: function () {
                            console.log('yes');
                            next(false);
                        }
                    }]
                });
            }
        },
        methods: {
            instHandlerClick() {
                // if (this.equipmentDetail === null || this.equipmentDetail === '' || this.equipmentDetail === undefined) {
                //
                // } else {
                //
                // }
                if (this.desfault !== '' || this.desfault !== null || this.desfault !== undefined) {
                    localStorage.setItem(repairEquipmentData,this.desfault);
                }
                this.$router.push({name: 'instList',params: {type:'repairEquipMent'}});
            },
            deleteImgHandler(payload) {
                var index = payload.index;
                this.$dialog.confirm({
                    title: '',
                    mes: '是否要删除该图片？',
                    opts: () => {
                        this.images.splice(index,1);
                    }
                });

            },
            async handleClick() {
                if ((this.desfault === '' || this.desfault === null) && this.images.length<=0) {
                    this.$dialog.toast({
                        mes: "请描述故障!",
                        timeout: 1500
                    });
                    return;
                }
                localStorage.removeItem(instObject);
                localStorage.removeItem(repairEquipmentData);
                this.$dialog.loading.open('发送中...');
                if (this.images.length > 0) {
                    this.orderApplyWXUploadImgFunc(this.images)
                } else {
                    this.orderApplyFunc('');
                }
            },
            orderApplyWXUploadImgFunc() {
                let that = this;
                wx.uploadImage({
                    localId: this.images[this.idx].toString(),
                    isShowProgressTips: 0,
                    success: function(res) {

                        // that.$dialog.confirm({
                        //     title: '测试微信图片上传',
                        //     mes: res.serverId,
                        //     opts: () => {
                        //         this.$dialog.toast({mes: '你点了确定', timeout: 1000});
                        //     }
                        // });

                        // 上传序号，上传一张 累计 +1
                        that.idx++;

                        //本地图片ID 还没全部获取完图片媒体ID
                        if (that.idx < that.images.length) {

                            //存储图片媒体ID，用，号分割
                            that.serverIds += res.serverId + ',';

                            //调用上传递归函数
                            that.orderApplyWXUploadImgFunc();
                        } else {
                            //存储图片媒体ID，用，号分割
                            that.serverIds += res.serverId;
                            //上传序号归零
                            that.idx=0;
                            that.uploadQiNiuImageFunc();
                        }
                    }
                })
            },
            async uploadQiNiuImageFunc() {

                // this.$dialog.confirm({
                //     title: '上传微信图片参数',
                //     mes: JSON.parse(localStorage.getItem(userInfoData)).mobile+'**'+this.serverIds,
                //     opts: () => {
                //         this.$dialog.toast({mes: '你点了确定', timeout: 1000});
                //     }
                // });

                var response = await uploadQiNiuImage(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,
                    this.serverIds,
                    localStorage.getItem(openId)
                );
                if (response.data.code === 200) {
                    this.orderApplyFunc(response.data.msg);
                    // this.$dialog.confirm({
                    //     title: '测试微信图片上传',
                    //     mes: response.data.msg,
                    //     opts: () => {
                    //         this.$dialog.toast({mes: '你点了确定', timeout: 1000});
                    //     }
                    // });
                } else {
                    this.$dialog.loading.close();
                    this.serverIds = '';
                    this.idx=0;
                    this.$dialog.toast({
                        mes: "上传图片失败，请重试！",
                        timeout: 1500
                    });
                }
            },
            async orderApplyFunc(image) {
                var response = await orderApply(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,
                    this.instUuid,
                    this.equipUuid,
                    this.faultTypeUuid,
                    this.desfault,
                    image
                );
                console.log(response);
                if (response.data.code === 200) {
                    this.$dialog.loading.close();
                    // var accessToken = localStorage.getItem(wxAccessToken);
                    // this.$dialog.confirm({
                    //     title: '测试微信图片上传',
                    //     mes: accessToken+'--***--'+this.serverIds,
                    //     opts: () => {
                    //         this.$dialog.toast({mes: '你点了确定', timeout: 1000});
                    //     }
                    // });
                    this.$dialog.toast({
                        mes: "设备报修成功！",
                        timeout: 1500
                    });

                    // this.$router.back();
                    // this.$router.replace({name: 'wait'});
                    //打开报修单详情界面
                    this.$router.replace({name: 'repairTask', params: {taskUUid: response.data.data.uuid,taskState: '00',isShowEvaluateDialog: false}});
                } else {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
            faultHandler() {
                this.isFaultSheet = true;
            },
            async showFaultTypeSelectFunc() {
                var response = await showFaultTypeSelect(JSON.parse(localStorage.getItem(userInfoData)).mobile);
                if (response.data.code === 200) {
                    var title = [{label: '请选择故障类型', callback: () => {}},];
                    var faultList = response.data.data;
                    var list = [];
                    var bean;
                    this.faultTypeUuid = faultList[3].uuid;
                    this.faultTypeStr = faultList[3].type_name;
                    for (var i = 0;i<faultList.length;i++) {
                        bean = {
                            label: faultList[i].type_name,
                            callback: (target) => {
                                console.log(target);
                                console.log(target.label);
                                this.faultTypeStr = target.label;
                                for (var j = 0;j<faultList.length;j++) {
                                    if (faultList[j].type_name === target.label) {
                                        this.faultTypeUuid = faultList[j].uuid
                                    }
                                }
                            }
                        };
                        list.push(bean);
                    }
                    this.faultItems = [...title,...list];
                } else {
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
            /** 开始录音事件 */
            touchStartAudio(payload) {
                let that = this;
                var localId = '';

                var touches = payload.event.touches[0];
                this.startTx = touches.clientX;
                this.startTy = touches.clientY;

                this.$dialog.loading.open('语音录制中...');

                wx.ready(function () {
                    wx.startRecord({
                        success: function () {
                            wx.onVoiceRecordEnd({
                                // 录音时间超过一分钟没有停止的时候会执行 complete 回调
                               complete: function (res) {
                                   that.$dialog.loading.close();
                                   localId = res.localId;
                                   // that.device = res.localId;
                                   // that.$dialog.confirm({
                                   //     title: '一分钟语音测试',
                                   //     mes: localId,
                                   //     opts: () => {
                                   //         that.$dialog.toast({mes: '你点了确定', timeout: 1000});
                                   //     }
                                   // });
                                   if (localId === '') {
                                       console.log('localId is "" ');
                                       that.desfault = '';
                                   } else {
                                       wx.ready(function () {
                                           wx.translateVoice({
                                               localId: localId, // 需要识别的音频的本地Id，由录音相关接口获得
                                               isShowProgressTips: 1, // 默认为1，显示进度提示
                                               success: function (res) {
                                                   // 语音识别的结果
                                                   that.desfault = res.translateResult;
                                               }
                                           });
                                       });
                                   }
                               }
                            });
                        }
                    });
                });
            },
            async machineUuidDetailsFunc(uuid,name) {
                var response = await machineUuidDetails(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,uuid);
                if (response.data.code === 200) {
                    var equipDetailBean = response.data.data;
                    // this.device = name;
                    // this.equipUuid = uuid;
                    //status,1为失效，0为有效  2报废

                    if (equipDetailBean.status === '1') {
                        this.$dialog.toast({
                            mes: '设备已删除',
                            timeout: 1500
                        });
                    } else if (equipDetailBean.status === '0'){
                        if (this.partnerUuid === equipDetailBean.partnerUuid) {
                            if (equipDetailBean.isBlank === '0') {
                                this.$dialog.toast({
                                    mes: '设备为空',
                                    timeout: 1500
                                });
                            } else if (equipDetailBean.isBlank === '1'){

                                this.$router.push({name: 'equipmentDetailrecord', params: {equipmentuuid: equipDetailBean.equipUuid,type:'2'}});
                            }
                        } else {
                            this.$dialog.toast({
                                mes: '不属于本机构的设备',
                                timeout: 1500
                            });
                        }

                    } else if(equipDetailBean.status === '2') {
                        this.$dialog.toast({
                            mes: '设备已报废',
                            timeout: 1500
                        });
                    }
                } else {
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
                // this.$dialog.confirm({
                //     title: '扫描二维码测试',
                //     mes: response.data,
                //     opts: () => {
                //         that.$dialog.toast({mes: '你点了确定', timeout: 1000});
                //     }
                // });
            },
            /** 停止录音事件 */
            touchEndAudio(payload) {
                let that = this;
                var localId = '';
                var touches = payload.event.changedTouches[0];
                var distanceY = this.startTy - touches.clientY;

                this.$dialog.loading.close();

                if (distanceY > 50) {
                    console.log("取消发送信息");
                    wx.stopRecord({
                        success: function (res) {
                            localId = res.localId;
                        }
                    })
                }else{
                    console.log("发送信息");

                    //停止录音接口
                    wx.ready(function () {
                        wx.stopRecord({
                            success: function (res) {
                                localId = res.localId;
                                // that.device = res.localId;
                                // that.$dialog.confirm({
                                //     title: '语音测试',
                                //     mes: localId,
                                //     opts: () => {
                                //         that.$dialog.toast({mes: '你点了确定', timeout: 1000});
                                //     }
                                // });
                                if (localId == '') {
                                    console.log('localId is "" ')
                                } else {
                                    wx.ready(function () {
                                        wx.translateVoice({
                                            localId: localId, // 需要识别的音频的本地Id，由录音相关接口获得
                                            isShowProgressTips: 1, // 默认为1，显示进度提示
                                            success: function (res) {
                                                // 语音识别的结果
                                                that.desfault = res.translateResult;
                                            }
                                        });
                                    });
                                }
                            }
                        });
                    });

                }
            },
            clickVoicePanel() {
                if (localStorage.getItem(rainAllowRecord) === '' || localStorage.getItem(rainAllowRecord) === null
                || localStorage.getItem(rainAllowRecord) === undefined || localStorage.getItem(rainAllowRecord) === '0') {
                    //没有授权过
                    wx.startRecord({
                       success: function () {
                           localStorage.setItem(rainAllowRecord,'1');
                           wx.stopRecord();
                       } ,
                        cancel: function () {
                            localStorage.setItem(rainAllowRecord,'0');
                        }
                    });
                }
            },
            /** 选择图片事件 */
            clickPicture() {
                console.log('clickPicture');
                let that = this;
                if (this.images.length < 3) {
                    wx.chooseImage({
                        count: 3-this.images.length, // 默认9
                        sizeType:['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['album'], //'album', 'camera' 可以指定来源是相册还是相机，默认二者都有
                        success: function (res) {
                            console.log('chooseImage success');
                            console.log(res);
                            console.log(res.localIds);
                            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                            that.images = [...that.images,...localIds];
                            // that.images = localIds;
                        }
                    });
                } else {
                    this.$dialog.toast({
                        mes: "已经达到最高选择数量",
                        timeout: 1500
                    });
                }
            },
            /** 拍照事件 */
            clickPhoto() {
                console.log('clickPhoto');
                let that = this;
                if (this.images.length < 3) {
                    wx.chooseImage({
                        count: 3-this.images.length, // 默认9
                        sizeType:['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                        success: function (res) {
                            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                            // that.images = localIds;
                            that.images = [...that.images,...localIds];
                        }
                    });
                } else {
                    this.$dialog.toast({
                        mes: "已经达到最高选择数量",
                        timeout: 1500
                    });
                }
            },
            scanHandleClick() {
                // var test = '{"appkey":"LittleBitDimension","uuid":"7f821b9322a243fd9461dcfc388281ef","name":"字符终端 跑马屏"}';
                // this.machineUuidDetailsFunc('7f821b9322a243fd9461dcfc388281ef','name');
                // this.$router.push({name: 'equipmentDetailrecord', params: {equipmentuuid:  'a179eaf22a0a4ed5ac97b8b732c08a33',type:'0'}});
                if (this.desfault !== '' || this.desfault !== null || this.desfault !== undefined) {
                    localStorage.setItem(repairEquipmentData,this.desfault);
                }
                if (this.equipmentDetail === null || this.equipmentDetail === '' || this.equipmentDetail === undefined) {
                    let that = this;
                    wx.scanQRCode({
                        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                        scanType: ["qrCode"], // "qrCode","barCode"可以指定扫二维码还是一维码，默认二者都有
                        success: function (res) {
                            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                            if (result.indexOf('LittleBitDimension') !== -1) {
                                var obj = JSON.parse(result);
                                that.machineUuidDetailsFunc(obj.uuid,obj.name);

                                // that.$router.push({name: 'equipmentDetailrecord', params: {equipmentuuid: obj.uuid,type:'2'}});
                            } else {
                                that.$dialog.toast({
                                    mes: "请扫描点点维的二维码!",
                                    timeout: 1500
                                });
                            }

                        }
                    });
                    //         if (test.indexOf('LittleBitDimension') !== -1) {
                    //             var obj = JSON.parse(test);
                    //             this.machineUuidDetailsFunc(obj.uuid,obj.name);
                    //
                    //             // that.$router.push({name: 'equipmentDetailrecord', params: {equipmentuuid: obj.uuid,type:'2'}});
                    //         } else {
                    //             this.$dialog.toast({
                    //                 mes: "请扫描点点维的二维码!",
                    //                 timeout: 1500
                    //             });
                    //         }
                    // console.log('scanHandleClick');
                    // this.$router.push({name: 'equipmentDetailrecord', params: {equipmentuuid:  'a179eaf22a0a4ed5ac97b8b732c08a33',type:'2'}});
                } else {
                    this.$router.push({name: 'equipmentDetailrecord', params: {equipmentuuid: this.equipmentDetail.machineUuid,type:'2'}});
                }
            },
            clickKeyboard() {
                this.isFocus = !this.isFocus;
                console.log(this.isFocus);
                if (this.isFocus === true) {
                    document.getElementById('textfocus').focus();
                } else {
                    document.getElementById('textfocus').blur();
                }
            },
            clickTextHandle() {
                this.isFocus = true;
                console.log(this.isFocus);
            },
            focusIpt() {
                this.isFocus = false;
                this.isMultimediaFocus = true;
                document.getElementById('textfocus').focus();
                // this.timer = setInterval(function() {
                //     document.body.scrollTop = document.body.scrollHeight
                // }, 200)
                // document.body.scrollTop = document.body.scrollHeight
            },
            blurIpt() {
                this.isFocus = true;
                this.isMultimediaFocus = false;
                document.getElementById('textfocus').blur();
                // clearInterval(this.timer);
            }
         },
    }
</script>

<style lang="scss">
    .repair-equipment-layout {
        padding: 0.75rem;

        .repair-content-part {

            /** 悬浮底部按钮 **/
            .buttom-tabbar {
                z-index: 200;
                position: fixed;
                bottom: 0;
                left: 0;
                width: 100%;
                transform: translateZ(200px);
                -ms-transform: translateZ(200px);
                -moz-transform: translateZ(200px);
                -webkit-transform: translateZ(200px);
                -o-transform: translateZ(200px);
            }

            .bottom-line {
                border-bottom: 1px solid #e6e6e6;
            }

            .yd-cell-item {
                align-items: center;
                &:after {
                    display: none;
                }
            }
            .yd-cell-left {
                align-items: flex-start;
            }
            .yd-cell-right {
                min-height: auto;
                height: 0.7rem;
                padding: 0rem;
                /*border-bottom: 1px solid #e6e6e6;*/
                //border-bottom: 1px solid transparent;
                //border-image: svg(1px-border param(--color #ebebeb)) 2 2 stretch;
                input {
                    height: 0.7rem !important;
                    padding-left: 0.1rem;
                }
            }
            .yd-cell-item {
                padding-left: 0;
            }

            .des-fault-part {
                border: 0;
                font-size: 1.2em;
                text-align: left;
                padding-top: 0.3rem;
                padding-left: 0.1rem;
            }

            .weui-btn {
                display: flex;
                height: 0.6rem;
                align-items: center;
                justify-content: center;
                font-size: 1.2em;
            }

            /*修改Input标签的placeholder文字颜色*/
            input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
                color: #9a9a9a;
            }
            input:-moz-placeholder, textarea:-moz-placeholder {
                color: #9a9a9a;
            }
            input::-moz-placeholder, textarea::-moz-placeholder {
                color: #9a9a9a;
            }
            input:-ms-input-placeholder, textarea:-ms-input-placeholder {
                color: #9a9a9a;
            }
        }
    }
</style>